<?php

namespace app\controller\api;

use app\service\cache\LocalDeviceInfoCacheService;
use app\exception\ErrnoPlus;
use app\service\AppMchTableService;
use app\service\LocalDeviceInfoService;
use app\validate\LocalDeviceInfoValidate;
use Exception;
use share\controller\ApiBaseController;
use share\exception\ApiException;
use share\service\ContextService;
use share\utils\Helper;

class LocalDeviceInfoController extends ApiBaseController
{

    protected $beforeActionList = [
        "checkSign",
        "checkUser",
    ];

    public function initValidate()
    {
        $this->validate = new LocalDeviceInfoValidate();
    }

    /**
     * 用户获取直连设备列表
     */
    public function list_action()
    {
        $this->check();
        $userInfo = ContextService::getUserInfo();
        $data = LocalDeviceInfoCacheService::getAllByFilter(['uid' => $userInfo['id']]);
        if (empty($data)) {
            return  self::fail("user does not have a local device", ErrnoPlus::NOT_BACK_DATA);
        }
        $res = Helper::listArrayColumn($data, [
            'serial_number' => 'serialNo',
            'ip' => 'ip',
            'port' => 'port',
            'nick_name' => 'nickName',
            'user_name' => 'userName',
            'password' => 'password',
            'type' => 'type',
        ]);
        return self::ok($res);
    }

    /**
     * 用户删除直连设备
     */
    public function del_action()
    {
        $input = $this->check();
        if (!is_array($input['serialNos']) || count($input['serialNos']) < 1) {
            throw new ApiException('serialNos is empty', ErrnoPlus::COMMON_ERROR);
        }
        $res = LocalDeviceInfoService::delLocalDevice($input);
        return self::ok($res);
    }


    /**
     * 用户修改直连设备
     */
    public function update_action()
    {
        $input = $this->check();
        $res = LocalDeviceInfoService::updateDevice($input);
        return self::ok($res);
    }

    /**
     * 用户新增直连设备
     */
    public function add_action()
    {
        $input = $this->check();
        $res = LocalDeviceInfoService::addDevice($input);
        return self::ok($res);
    }
}
